-- Constants
local gotDailies = gotDailies
local continents = {GetMapContinents()}
local zones = {}
for i=1,#continents do
	zones[i] = {GetMapZones(i)}
	table.sort(zones[i])
end

local genericbackdrop = {	
				bgFile = "Interface/ChatFrame/ChatFrameBackground", 
                                edgeFile = "Interface/Tooltips/UI-Tooltip-Border", 
                                tile = true, tileSize = 16, edgeSize = 16, 
                                insets = { left = 3, right = 3, top = 5, bottom = 3 }
			}

local settings = gotDailiesSettings
if not settings then
	return ChatFrame1:AddMessage("Could not find gotDailies settings table.")
end

local ScanTooltip = CreateFrame("GameTooltip", "gotDailies_ScanTip", UIParent, "GameTooltipTemplate")
local ScanTooltipQuestName = gotDailies_ScanTipTextLeft1
ScanTooltip:SetOwner(UIParent, "ANCHOR_NONE")

local function ClearDropDown(dropdown)
	dropdown.selectedID = nil;
	dropdown.selectedName = nil;
	dropdown.selectedValue = nil;
	UIDropDownMenu_SetText(dropdown, "")
end

local function GetContinentForZone(zone)
	for continentindex, continent in ipairs(continents) do
		for zoneindex, zonename in ipairs(zones[continentindex]) do
			if zonename == zone then
				return continentindex, continent, zoneindex
			end
		end
	end
end

-- Add entry to table, avoiding duplicates.
local function AddValueOnce(t, value)
	for i=1, #t do
		if t[i] == value then
			return
		end
	end
	t[#t + 1] = value
end

-- General addon settings.
local frame = CreateFrame("Frame", "gotDailiesConfig")
frame.name = "gotDailies"

--Titletext and subtext.
local title = frame:CreateFontString(nil, "ARTWORK", "GameFontNormalLarge")
title:SetText("gotDailies?")
title:SetJustifyH("LEFT")
title:SetJustifyV("TOP")
title:SetPoint("TOPLEFT", 16, -16)

local subText = frame:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall")
subText:SetText("gotDailies helps you with your dailies by automatically picking the appropriate item to use.")
subText:SetJustifyH("LEFT")
subText:SetJustifyV("TOP")
subText:SetPoint("TOPLEFT", title, "BOTTOMLEFT", 0, -8)
subText:SetPoint("RIGHT", -32, 0)
subText:SetHeight(subText:GetStringHeight()*math.ceil(subText:GetStringWidth()/InterfaceOptionsFramePanelContainer:GetWidth())+5)


local function ButtonOnEnter(frame) 
	GameTooltip:SetOwner(frame, "ANCHOR_RIGHT")
	GameTooltip:AddLine(frame.tooltip, 1,1,1,1)
	GameTooltip:Show()
end

button = CreateFrame("CheckButton", "gotDailiesHideEmpty", frame, "InterfaceOptionsCheckButtonTemplate")
button:SetWidth(24)
button:SetHeight(24)
button:SetPoint("TOPLEFT", subText, "BOTTOMLEFT", 0, -5)
button.var = "hideempty"
button.text = gotDailiesHideEmptyText
button.text:SetText("Hide empty buttons.")
button:SetScript("OnClick", function(self) settings[self.var] = not not self:GetChecked() end)
previous = button

button = CreateFrame("CheckButton", "gotDailiesRangeCheck", frame, "InterfaceOptionsCheckButtonTemplate")
button:SetWidth(24)
button:SetHeight(24)
button:SetPoint("TOPLEFT", previous, "BOTTOMLEFT", 0, -5)
button.var = "rangecheck"
button.text = gotDailiesRangeCheckText
button.text:SetText("Color buttons red when they're out of range.")
button:SetScript("OnClick", function(self) settings[self.var] = not not self:GetChecked() end)
previous = button

button = CreateFrame("CheckButton", "gotDailiesPrioFirst", frame, "InterfaceOptionsCheckButtonTemplate")
button:SetWidth(24)
button:SetHeight(24)
button:SetPoint("TOPLEFT", previous, "BOTTOMLEFT", 0, -5)
button.var = "priofirst"
button.text = gotDailiesPrioFirstText
button.text:SetText("Prioritize the first button.")
button.tooltip = "When this is checked, gotDailies will always attempt to fill the first button, and move others up when it becomes available."
button:SetScript("OnEnter", ButtonOnEnter)
button:SetScript("OnLeave", function() GameTooltip:Hide() end)
button:SetScript("OnClick", function(self) settings[self.var] = not not self:GetChecked() end)
previous = button

button = CreateFrame("CheckButton", "gotDailiesShowTooltip", frame, "InterfaceOptionsCheckButtonTemplate")
button:SetWidth(24)
button:SetHeight(24)
button:SetPoint("TOPLEFT", previous, "BOTTOMLEFT", 0, -5)
button.var = "tooltip"
button.text = gotDailiesShowTooltipText
button.text:SetText("Show ability tooltips.")
button:SetScript("OnClick", function(self) settings[self.var] = not not self:GetChecked() end)

frame:SetScript("OnShow", function(self)
	local object
	for i=1, select("#", self:GetChildren()) do
		object = select(i, self:GetChildren())
		if object.var then
			object:SetChecked(settings[object.var])
		end
	end
end)

InterfaceOptions_AddCategory(frame)

-- Quest List
local list = CreateFrame("Frame")
list.name = "QuestList"
list.parent = "gotDailies"

local elements = {}
local buttons = {}

local function ClearAll()
	elements.questid:SetNumber("")
	elements.questid.questname:SetText("")
	ClearDropDown(elements.continent)
	ClearDropDown(elements.zonemajor)
	
	elements.action.contents = {}
	elements.subzone.contents = {}
	
	buttons.defaults:Disable()
end
	

-- Sets up the edit quest fields.
local function SetQuest(questid, zone)
	ClearAll()
	elements.questid:SetNumber(questid)
	
	-- Make the questname update.
	elements.questid:SetFocus()
	elements.questid:ClearFocus()
	
	local questdata = gotDailies.QuestList[questid]

	if not zone then
		zone = questdata and questdata.zoneMajor or GetRealZoneText()
	end
	

	local index, continent = GetContinentForZone(zone)
	elements.zonemajor.continent = index
	elements.continent.selectedID = index
	UIDropDownMenu_SetText(elements.continent, continent)
	
	elements.zonemajor.selectedValue = zone
	UIDropDownMenu_SetText(elements.zonemajor, zone)

	
	if questdata then
		elements.priority:SetText(questdata.prio or "")
		
		local actions = questdata.action
		if type(actions) == "table" then
			for actionset=1, #actions do
				local action = actions[actionset]
				local entries = #action
				
				elements.action.contents[actionset] = action[entries]
				elements.subzone.contents[actionset] = table.concat(action, ", ", 1, entries-1)
			end
		else
			if type(questdata.zoneMinor) == "table" then
				elements.subzone.contents[1] = table.concat(questdata.zoneMinor, ", ")
			else
				elements.subzone.contents[1] = questdata.zoneMinor
			end
			elements.action.contents[1] = actions
		end
		
		elements.action:SetCursorPosition(0)
		elements.subzone:SetCursorPosition(0)
		
		elements.action:Update(1)
		elements.subzone:Update(1)
		
		if rawget(gotDailies.QuestList, questid) and getmetatable(gotDailies.QuestList).__index[questid] then
			buttons.defaults:SetText("Defaults")
		elseif rawget(gotDailies.QuestList, questid) then
			buttons.defaults:SetText("Delete")
		else
			return buttons.defaults:Disable()
		end
		buttons.defaults:Enable()
	else
		buttons.defaults:Disable()
	end
end

local function ProcessForm()
	if elements.questid.questname.quest then
		local questid = elements.questid:GetNumber()
		local questname = elements.questid.questname:GetText()
		local zoneMajor = elements.zonemajor.selectedValue
		local action, zoneMinor
		local entries = #elements.action.contents
		if entries > 1 then
			zoneMinor = {}
			action = {}
			for i=1, entries do
				local actiontext = elements.action.contents[i]
				local zonetext = elements.subzone.contents[i]
				
				if actiontext ~= "" then
					local t = {}
					for zone in zonetext:gmatch("[^,]+") do
						zone = strtrim(zone)
						AddValueOnce(t, zone)
						AddValueOnce(zoneMinor, zone)
					end
					
					t[#t+1] = tonumber(actiontext) or actiontext
					action[#action+1] = t
				end
			end
		else
			local actiontext = elements.action.contents[1]
			local zonetext = elements.subzone.contents[1]
			
			if actiontext == "" or zonetext == "" then
				return print("|cffff0000gotDailies: You forgot to enter action or zone data. At least the first action and zone fields must be completed.")
			end
			
			action = tonumber(actiontext) or actiontext
			if zonetext:find(",") then
				zoneMinor = {}
				for zone in zonetext:gmatch("[^,]+") do
					zone = zone:gsub("^%s*(.+)%s*$", "%1")
					AddValueOnce(zoneMinor, zone)
				end
			else
				zoneMinor = zonetext
			end
		end
		
		local t = rawget(gotDailies.QuestList, questid)
		if t then
			-- Clean up the existing action table so the GC collects all the subtables.
			if type(t.action) == "table" then
				wipe(t.action)
			end
		end
		
		t = t or {}
		t.questname = questname
		t.zoneMajor = zoneMajor
		t.zoneMinor = zoneMinor
		t.action = action
		t.prio = tonumber(elements.priority:GetText())
		
		gotDailies.QuestList[questid] = t
		
		SetQuest(questid)
		
		gotDailies:CheckQuest(questname, questid)
		gotDailies:UpdateButtons()
	else
		print("The quest you're trying to add could not be found.")
	end	
end

local function RestoreDefaults(self)
	local questid = elements.questid:GetNumber()
	
	local data = rawget(gotDailies.QuestList, questid)
	data.zoneMinor = nil
	if type(data.action) == "table" then
		wipe(data.action)
	end
	gotDailies.QuestList[questid] = nil
	data = nil
	
	if not gotDailies.QuestList[questid] then
		ClearDropDown(elements.selectquest_zonemajor)
		ClearDropDown(elements.selectquest_questname)
	end
	
	SetQuest(questid)
end

-- Titletext and subtext.
local title = list:CreateFontString(nil, "ARTWORK", "GameFontNormalLarge")
title:SetText("QuestList")
title:SetJustifyH("LEFT")
title:SetJustifyV("TOP")
title:SetPoint("TOPLEFT", 16, -16)

local subText = list:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall")
subText:SetText("You can use the menu below to change or add questlist entries.")
subText:SetJustifyH("LEFT")
subText:SetJustifyV("TOP")
subText:SetPoint("TOPLEFT", title, "BOTTOMLEFT", 0, -8)
subText:SetPoint("RIGHT", -32, 0)
subText:SetHeight(subText:GetStringHeight()*math.ceil(subText:GetStringWidth()/InterfaceOptionsFramePanelContainer:GetWidth())+5)


local selectquestframe = CreateFrame("Frame", nil, list)
selectquestframe:SetPoint("TOPLEFT", subText, "BOTTOMLEFT", 0, -20)
selectquestframe:SetWidth(381)
selectquestframe:SetHeight(90)
selectquestframe:SetBackdrop(genericbackdrop)
selectquestframe:SetBackdropColor(0.1,0.1,0.1,0.5)
selectquestframe:SetBackdropBorderColor(0.4,0.4,0.4)

selectquestframe.title = selectquestframe:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
selectquestframe.title:SetPoint("TOPLEFT", 4, 12)
selectquestframe.title:SetText("Select quest to edit:")

local dropdown1 = CreateFrame("Frame", "gotDailies_SelectZoneMajor", selectquestframe, "UIDropDownMenuTemplate")
dropdown1:SetPoint("TOPLEFT", selectquestframe, "TOPLEFT", -8, -16)
dropdown1.text = dropdown1:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
dropdown1.text:SetPoint("TOPLEFT", 20, 10)
dropdown1.text:SetText("Zone Name")
UIDropDownMenu_SetWidth(dropdown1, 150)
elements.selectquest_zonemajor = dropdown1

local function selectquestzone_OnClick(self)
	UIDropDownMenu_SetSelectedValue(dropdown1, self.value)
end

local function selectquestzone_Initialize()
	local info = UIDropDownMenu_CreateInfo()
	local zonelist = gotDailies:GetQuestsPerZone()
	for zone, quests in pairs(zonelist) do
		if #quests > 0 then
			info.text = zone
			info.func = selectquestzone_OnClick
			info.checked = nil
			UIDropDownMenu_AddButton(info)
		end
	end
	zonelist = nil
end

UIDropDownMenu_Initialize(dropdown1, selectquestzone_Initialize)

local dropdown2 = CreateFrame("Frame", "gotDailies_SelectQuestName", list, "UIDropDownMenuTemplate")
dropdown2:SetPoint("LEFT", dropdown1, "RIGHT", -20, 0)
dropdown2.text = dropdown2:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
dropdown2.text:SetPoint("TOPLEFT", 20, 10)
dropdown2.text:SetText("Quest Name")
UIDropDownMenu_SetWidth(dropdown2, 160)
elements.selectquest_questname = dropdown2

local function selectquestname_OnClick(self)
	UIDropDownMenu_SetSelectedValue(dropdown2, self.value)
	ClearDropDown(elements.selectquest_fromlog)
	SetQuest(self.value, dropdown1.selectedValue)
end

local function selectquestname_Initialize()
	local info = UIDropDownMenu_CreateInfo()
	local questlist = gotDailies:GetQuestsPerZone()
	local zone = UIDropDownMenu_GetSelectedValue(dropdown1)
	if questlist[zone] then
		for i, questid in ipairs(questlist[zone]) do
			info.text = gotDailies.QuestList[questid].questname or questid
			info.value = questid
			info.func = selectquestname_OnClick
			info.checked = nil
			UIDropDownMenu_AddButton(info)
		end
	end
end

UIDropDownMenu_Initialize(dropdown2, selectquestname_Initialize)

local selectfromlog = CreateFrame("Frame", "gotDailies_SelectQuestFromLog", list, "UIDropDownMenuTemplate")
selectfromlog:SetPoint("TOPLEFT", dropdown1, "BOTTOMLEFT", 0, -8)
selectfromlog.text = selectfromlog:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
selectfromlog.text:SetPoint("TOPLEFT", 20, 10)
selectfromlog.text:SetText("Select quest from questlog")
UIDropDownMenu_SetWidth(selectfromlog, 200)
elements.selectquest_fromlog = selectfromlog

local function selectfromlog_OnClick(self)
	UIDropDownMenu_SetSelectedValue(selectfromlog, self.value)
	ClearDropDown(elements.selectquest_questname)
	ClearDropDown(elements.selectquest_zonemajor)
	SetQuest(self.value)
end

local function selectfromlog_Initialize()
	local dailyonly = elements.dailyonly and elements.dailyonly:GetChecked()
	local info = UIDropDownMenu_CreateInfo()
	for i=1,50 do
		local name, _, _, _, isHeader, _, _, isDaily, questID = GetQuestLogTitle(i)
		if not name then return end
		if not isHeader and not dailyonly or isDaily then
			if questID then
				info.text = name
				info.value = questID
				info.func = selectfromlog_OnClick
				info.checked = nil
				UIDropDownMenu_AddButton(info)
			end
		end
	end
end

UIDropDownMenu_Initialize(selectfromlog, selectfromlog_Initialize)

local dailyonly = CreateFrame("CheckButton", "gotDailies_dailyonly", selectquestframe, "UICheckButtonTemplate")
dailyonly:SetPoint("LEFT", selectfromlog, "RIGHT", 0, 0)
dailyonly:SetWidth(24)
dailyonly:SetHeight(24)
dailyonly.text = _G["gotDailies_dailyonly".."Text"]
dailyonly.text:SetText("Daily quests only.")
elements.dailyonly = dailyonly

local questframe = CreateFrame("Frame", nil, list)
questframe:SetPoint("TOPLEFT", selectquestframe, "BOTTOMLEFT", 0, -20)
questframe:SetPoint("BOTTOMRIGHT", list, "BOTTOMRIGHT", -16, 16)
questframe:SetBackdrop(genericbackdrop)
questframe:SetBackdropColor(0.1,0.1,0.1,0.5)
questframe:SetBackdropBorderColor(0.4,0.4,0.4)

questframe.title = questframe:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
questframe.title:SetPoint("TOPLEFT", 4, 12)
questframe.title:SetText("Edit quest")

local newquestframe = CreateFrame("Frame", nil, list)
newquestframe:SetPoint("TOPLEFT", questframe, "TOPLEFT")
newquestframe:SetPoint("BOTTOMRIGHT", questframe, "TOPRIGHT", 0, -83)
newquestframe:SetBackdrop(genericbackdrop)
newquestframe:SetBackdropColor(0.1,0.1,0.1,0.5)
newquestframe:SetBackdropBorderColor(0.4,0.4,0.4)
newquestframe.shown = true

local priority = CreateFrame("EditBox", "gotDailies_Priority", newquestframe, "InputBoxTemplate")
priority:SetFontObject("GameFontNormalSmall")
priority:SetTextColor(1,1,1)
priority:SetWidth(30)
priority:SetHeight(12)
priority:SetPoint("TOPRIGHT", -16, -20)
priority:SetAutoFocus(false)

priority.title = priority:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
priority.title:SetPoint("TOPLEFT", 0, 12)
priority.title:SetText("Prio")
elements.priority = priority

local questid = CreateFrame("EditBox", "gotDailies_QuestID", newquestframe, "InputBoxTemplate")
questid:SetFontObject("GameFontNormalSmall")
questid:SetTextColor(1,1,1)
questid:SetWidth(80)
questid:SetHeight(12)
questid:SetPoint("TOPLEFT", 16, -20)
questid:SetAutoFocus(false)
questid:SetNumeric(true)

local function QuestIDClearFocus(self)
	self:ClearFocus()
	ClearDropDown(elements.selectquest_questname)
	ClearDropDown(elements.selectquest_zonemajor)
end

questid:SetScript("OnEscapePressed", QuestIDClearFocus)
questid:SetScript("OnEnterPressed", QuestIDClearFocus)
questid:SetScript("OnEditFocusLost", function(self)
	local num = self:GetNumber()
	
	self.questlink = string.format("|Hquest:%d|h%s|h", num, "%s")
	ScanTooltip:ClearLines()
	ScanTooltip:SetHyperlink(self.questlink)
	local questname = ScanTooltipQuestName:GetText()
	if questname then
		self.questname.quest = string.format("|Hquest:%d|h[%s]|h", num, questname)
		self.questname:SetText(questname)
		self.questname:SetTextColor(1,1,1)
	else
		self.questname.quest = nil
		self.questname:SetText("Querying server...")
		self.questname:SetTextColor(1,1,0)
		self.query = 1
	end
	self:HighlightText(0,0)
end)

questid:SetScript("OnUpdate", function(self, elapsed)
	if self.query then
		self.query = self.query - elapsed
		if self.query <= 0 then
			ScanTooltip:ClearLines()
			ScanTooltip:SetHyperlink(self.questlink)
			local questname = ScanTooltipQuestName:GetText()
			if questname then
				self.questname.quest = string.format(self.questlink, questname)
				self.questname:SetText(questname)
				self.questname:SetTextColor(1,1,1)
			else
				self.questname.quest = nil
				self.questname:SetText("Quest not found in quest cache.")
				self.questname:SetTextColor(1,0,0)
			end
			self.query = nil
		end
	end
end)

questid.title = questid:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
questid.title:SetPoint("TOPLEFT", 0, 12)
questid.title:SetText("QuestID")
elements.questid = questid

local questnamelabel = questid:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
questnamelabel:SetPoint("TOPLEFT", questid, "TOPRIGHT", 24, 12)
questnamelabel:SetText("Quest Name")

local questname = questid:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
questname:SetPoint("LEFT", questid, "RIGHT", 25, 0)
questname:SetPoint("RIGHT", priority, "LEFT", -16, 0)
questname:SetHeight(20)
questname:SetTextColor(1,1,1)
questname:SetJustifyH("LEFT")

local questnameframe = CreateFrame("Frame",nil,questid)
questnameframe.questname = questname
questnameframe:EnableMouse(true)
questnameframe:SetAllPoints(questname)
questnameframe:SetScript("OnEnter", function(self)
	if self.questname.quest then
		GameTooltip:SetOwner(self, "ANCHOR_TOPLEFT")
		GameTooltip:SetHyperlink(self.questname.quest)
	end
end)

questnameframe:SetScript("OnLeave", function(self)
	if GameTooltip:IsOwned(self) then
		GameTooltip:Hide()
	end
end)

questid.questname = questname

local questnameleft = questid:CreateTexture(nil, "BACKGROUND")
questnameleft:SetPoint("LEFT", questid, "RIGHT", 20, 0)
questnameleft:SetTexture([[Interface\Common\Common-Input-Border]])
questnameleft:SetWidth(8)
questnameleft:SetHeight(20)
questnameleft:SetTexCoord(0, 0.0625, 0, 0.625)

local questnameright = questid:CreateTexture(nil, "BACKGROUND")
questnameright:SetPoint("RIGHT", questname, "RIGHT", 4, 0)
questnameright:SetTexture([[Interface\Common\Common-Input-Border]])
questnameright:SetWidth(8)
questnameright:SetHeight(20)
questnameright:SetTexCoord(0.9375, 1, 0, 0.625)

local questnamemiddle = questid:CreateTexture(nil, "BACKGROUND")
questnamemiddle:SetPoint("LEFT", questname, "LEFT")
questnamemiddle:SetPoint("RIGHT", questname, "RIGHT")
questnamemiddle:SetHeight(20)
questnamemiddle:SetTexture([[Interface\Common\Common-Input-Border]])
questnamemiddle:SetTexCoord(0.0625, 0.9375, 0, 0.625)

local continent = CreateFrame("Frame", "gotDailies_EditQuestSelectContinent", newquestframe, "UIDropDownMenuTemplate")
continent:SetPoint("TOPLEFT", questid, "BOTTOMLEFT", -22, -16)
continent.text = continent:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
continent.text:SetPoint("TOPLEFT", 20, 10)
continent.text:SetText("Continent")
UIDropDownMenu_SetWidth(continent, 130)
elements.continent = continent

local zonemajor = CreateFrame("Frame", "gotDailies_EditQuestSelectZoneMajor", newquestframe, "UIDropDownMenuTemplate")
zonemajor:SetPoint("LEFT", continent, "RIGHT", -22, 0)
zonemajor.text = zonemajor:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
zonemajor.text:SetPoint("TOPLEFT", 20, 10)
zonemajor.text:SetText("Zone Name")
UIDropDownMenu_SetWidth(zonemajor, 182)
elements.zonemajor = zonemajor

zonemajor_OnClick = function(self)
	UIDropDownMenu_SetSelectedValue(zonemajor, self.value)
end

local function zonemajor_Initialize()
	if not zonemajor.continent then return end
	local info = UIDropDownMenu_CreateInfo()
	local zonelist = zones[zonemajor.continent]
	for i=1, #zonelist do
		info.text = zonelist[i]
		info.func = zonemajor_OnClick
		info.checked = nil
		UIDropDownMenu_AddButton(info)
	end
end
UIDropDownMenu_Initialize(zonemajor, zonemajor_Initialize)

local function continent_OnClick(self)
	local id = self:GetID()
	UIDropDownMenu_SetSelectedID(continent, id)
	zonemajor.continent = id
end

-- Shameless rip from Blizzard.
local function continent_Initialize(...)
	local info = UIDropDownMenu_CreateInfo();
	for i=1, #continents, 1 do
		info.text = continents[i];
		info.func = continent_OnClick
		info.checked = nil;
		UIDropDownMenu_AddButton(info);
	end
end
UIDropDownMenu_Initialize(continent, continent_Initialize)

local function EditBoxShowHelp(self)
	GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
	GameTooltip:AddLine(self.help)
	GameTooltip:Show()
end

local function OnLeave()
	GameTooltip:ClearLines()
	GameTooltip:Hide()
end

local function Update(self, pos)
	self:SetText(self.contents[pos])
end

local subzone = CreateFrame("EditBox", "gotDailies_SubzoneEditBox", questframe, "InputBoxTemplate")
subzone:SetFontObject("GameFontNormalSmall")
subzone:SetTextColor(1,1,1)
subzone:SetHeight(12)
subzone:SetPoint("TOPLEFT", newquestframe, "BOTTOMLEFT", 16, -12)
subzone:SetPoint("RIGHT", questframe, "RIGHT", -16, 0)
subzone:SetAutoFocus(false)

subzone:SetScript("OnEscapePressed", subzone.ClearFocus)
subzone:SetScript("OnEnterPressed", subzone.ClearFocus)
subzone:SetScript("OnEnter", ShowSubZoneHelp)
subzone:SetScript("OnLeave", OnLeave)
subzone:SetScript("OnTabPressed", function(self)
	self:ClearFocus()
	elements.action:SetFocus()
end)

subzone.title = subzone:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
subzone.title:SetPoint("TOPLEFT", 0, 12)
subzone.title:SetText("Subzone:")

subzone.Update = Update
subzone.help = "Enter subzones for this action. At least one subzone needs to be given. \nSeperate multiple zones with a comma.\n'all' (without quotes) may be used to match all subzones in zoneMajor."
subzone.contents = {}

elements.subzone = subzone

local actionBackground = CreateFrame("Frame", nil, questframe)
actionBackground:SetBackdrop(genericbackdrop)
actionBackground:SetBackdropColor(0,0,0, 0.5)
actionBackground:SetPoint("TOPLEFT", subzone, "BOTTOMLEFT", -5, -20)
actionBackground:SetPoint("RIGHT", questframe, "RIGHT", -16, 0)
actionBackground:SetHeight(75)

actionBackground.title = actionBackground:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
actionBackground.title:SetPoint("TOPLEFT", 5, 12)
actionBackground.title:SetText("Action:")

local actionScrollFrame = CreateFrame("ScrollFrame", "gotDailies_ActionEditScrollFrame", actionBackground, "UIPanelScrollFrameTemplate")
actionScrollFrame:SetPoint("TOPLEFT", actionBackground, "TOPLEFT", 5, -5)
actionScrollFrame:SetPoint("BOTTOMRIGHT", actionBackground, "BOTTOMRIGHT", -27, 5)
actionScrollFrame:SetWidth(320)
actionScrollFrame:SetHeight(65)


local action = CreateFrame("EditBox", "gotDailies_ActionEditBox", subzone)
action:SetFontObject("GameFontNormalSmall")
action:SetTextColor(1,1,1)
action:SetWidth(320)
action:SetHeight(70)
action:SetAutoFocus(false)
action:SetMultiLine()
actionScrollFrame:SetScrollChild(action)

action.Update = Update
action.help = "Action can be either an itemID or a macro."
action.contents = {}

action:SetScript("OnEscapePressed", action.ClearFocus)
action:SetScript("OnEnterPressed", function(self)
	self:Insert("\n")
end)
action:SetScript("OnTextChanged", function(self)
	ScrollingEdit_OnTextChanged(self, self:GetParent())
end)
action:SetScript("OnCursorChanged", ScrollingEdit_OnCursorChanged)
action:SetScript("OnEnter", EditBoxShowHelp)
action:SetScript("OnUpdate", function(self, elapsed)
	ScrollingEdit_OnUpdate(self, elapsed, self:GetParent())
end)
action:SetScript("OnLeave", OnLeave)
action:SetScript("OnTabPressed", function(self)
	self:ClearFocus()
	elements.subzone:SetFocus()
end)
action.cursorOffset = 0

elements.action = action


-- Bottom buttons.
local helpbutton = CreateFrame("Button", "gotDailies_ClearQuestForm", questframe, "UIPanelButtonTemplate2")
helpbutton:SetPoint("BOTTOMRIGHT", -4, 4)
helpbutton:SetWidth(50)
helpbutton:Hide()

helpbutton.text = gotDailies_ClearQuestFormText
helpbutton.text:SetText("Help")
buttons.help = helpbutton

local defaultsbutton = CreateFrame("Button", "gotDailies_defaultsbutton", questframe, "UIPanelButtonTemplate2")
defaultsbutton:SetPoint("BOTTOM", 0, 4)
defaultsbutton:SetWidth(60)
defaultsbutton:Disable()
defaultsbutton:SetScript("OnClick", RestoreDefaults)

defaultsbutton.text = gotDailies_defaultsbuttonText
defaultsbutton.text:SetText("Default")

buttons.defaults = defaultsbutton

local clearbutton = CreateFrame("Button", "gotDailies_SaveQuest", questframe, "UIPanelButtonTemplate2")
clearbutton:SetPoint("LEFT", defaultsbutton, "RIGHT", 5, 0)
clearbutton:SetWidth(50)

clearbutton.text = gotDailies_SaveQuestText
clearbutton.text:SetText("Clear")
clearbutton:SetScript("OnClick", ClearAll)
buttons.clear = clearbutton

local savebutton = CreateFrame("Button", "gotDailies_savebutton", questframe, "UIPanelButtonTemplate2")
savebutton:SetPoint("RIGHT", defaultsbutton, "LEFT", -5, 0)
savebutton:SetWidth(50)

savebutton.text = gotDailies_savebuttonText
savebutton.text:SetText("Save")
savebutton:SetScript("OnClick", ProcessForm)
buttons.save = savebutton

local function OnEnter(self)
	if not self.disabled then
		self.text:SetTextColor(1,1,1)
	end
end

local function OnLeave(self)
	if not self.disabled then
		self.text:SetTextColor(1, 215/255, 0)
	end
end

local function OnMouseUp(self)
	if not self.disabled then
		ChangePage(self.dir)
	end
end

local prev = CreateFrame("Frame", nil, questframe)
prev:SetPoint("BOTTOMLEFT", 7, 7)
prev:EnableMouse()
prev:SetScript("OnEnter", OnEnter)
prev:SetScript("OnLeave", OnLeave)
prev:SetScript("OnMouseUp", OnMouseUp)
prev.dir = -1
prev.disabled = true

prev.text = prev:CreateFontString(nil, "OVERLAY", "GameFontNormal")
prev.text:SetText("<")
prev.text:SetAllPoints(prev)
prev.text:SetTextColor(170/255, 170/255, 170/255)
prev:SetWidth(prev.text:GetStringWidth())
prev:SetHeight(prev.text:GetStringHeight())

elements.prev = prev

local page = questframe:CreateFontString(nil, "OVERLAY", "GameFontNormal")
page:SetPoint("LEFT", prev, "RIGHT", 4, 0)
page:SetText("Page 1")

elements.page = page

local next = CreateFrame("Frame", nil, questframe)
next:SetPoint("LEFT", page, "RIGHT", 4, 0)
next:EnableMouse()
next:SetScript("OnEnter", OnEnter)
next:SetScript("OnLeave", OnLeave)
next:SetScript("OnMouseUp", OnMouseUp)
next.dir = 1

next.text = next:CreateFontString(nil, "OVERLAY", "GameFontNormal")
next.text:SetText(">")
next.text:SetAllPoints(next)
next.text:SetTextColor(1, 215/255, 0)
next:SetWidth(next.text:GetStringWidth())
next:SetHeight(next.text:GetStringHeight())

elements.next = next

InterfaceOptions_AddCategory(list)